import api from "../../api/index.js";
Component({
  properties: {
    list: {
      type: Array,
      value: []
    },
    modalType: {
      type: Number,
      value: 1 //1:删除模式，2是选择模式
    },
  },

  data: {
    addressList: [],
    showModal: false,
    isEdit: false,
    currentAddress: {
      receiver: '',
      mobile: '',
      addressName: '',
      address: ''
    },
    editIndex: -1,
    modalHeight: 520,
    deleteIndex: -1
  },

  observers: {
    'list': function (list) {
      this.setData({
        addressList: list
      });
    }
  },

  lifetimes: {
    attached() {
      this.dialog = this.selectComponent('#delete-dialog');

      // 根据屏幕高度计算弹窗高度
      wx.getSystemInfo({
        success: (res) => {
          this.setData({
            modalHeight: res.windowHeight * 0.7
          });
        }
      });
    }
  },

  methods: {
    initEmptyAddress() {
      return {
        name: '',
        phone: '',
        title: '',
        detail: ''
      };
    },

    onAdd() {
      this.setData({
        showModal: true,
        isEdit: false,
        currentAddress: this.initEmptyAddress(),
        editIndex: -1
      });
    },

    onEdit(e) {
      const index = e.currentTarget.dataset.index;
      const address = this.data.addressList[index];

      this.setData({
        showModal: true,
        isEdit: true,
        currentAddress: {
          ...address
        },
        editIndex: index
      });
    },

    showDeleteDialog(e) {
      const index = e.currentTarget.dataset.index;
      const id = e.currentTarget.dataset.id;
      wx.showModal({
        title: '提示',
        content: '确定要删除该地址吗？',
        success: (res) => {
          if (res.confirm) {
            api.addressDel({
              method: "GET",
              id: id,
            }).then((res) => {
              const addressList = [...this.data.addressList];
              addressList.splice(index, 1);
              this.setData({
                addressList
              });
              this.triggerEvent('change', {
                addressList
              });
            })
          }
        }
      });
    },

    onDeleteConfirm() {
      const index = this.data.deleteIndex;
      const addressList = [...this.data.addressList];
      addressList.splice(index, 1);

      this.setData({
        addressList,
        deleteIndex: -1
      });

      this.triggerEvent('change', {
        addressList
      });
      wx.showToast({
        title: '删除成功',
        icon: 'success'
      });
    },

    onInputChange(e) {
      const {
        field
      } = e.currentTarget.dataset;
      const value = e.detail;
      this.setData({
        [`currentAddress.${field}`]: value
      });
    },

    onCancel() {
      const original = this.data.isEdit ?
        this.data.addressList[this.data.editIndex] :
        this.initEmptyAddress();

      const changed = Object.keys(original).some(
        key => this.data.currentAddress[key] !== original[key]
      );

      if (changed) {
        wx.showModal({
          title: '提示',
          content: '您有未保存的修改，确定要放弃吗？',
          success: (res) => {
            if (res.confirm) {
              this.setData({
                showModal: false
              });
            }
          }
        });
      } else {
        this.setData({
          showModal: false
        });
      }
    },
    tapAddressDetail() {
      let that = this
      let currentAddress = this.data.currentAddress
      wx.chooseLocation({
        success: function (res) {
          currentAddress.address = res.address
          currentAddress.addressName = res.name
          currentAddress.longitude = res.longitude
          currentAddress.latitude = res.latitude
          that.setData({
            currentAddress
          }, function () {
            console.info("22222222")
          })
        },
        fail: function (err) {
          console.info("chooseLocation::" + JSON.stringify(err))
        }
      })
    },
    onConfirm() {
      const {
        currentAddress,
        isEdit,
        editIndex,
        addressList
      } = this.data;
      // 验证
      if (!currentAddress.receiver) {
        wx.showToast({
          title: '请填写收件人姓名',
          icon: 'none'
        });
        return;
      }

      if (!currentAddress.mobile) {
        wx.showToast({
          title: '请填写手机号',
          icon: 'none'
        });
        return;
      }

      if (!/^1[3-9]\d{9}$/.test(currentAddress.mobile)) {
        wx.showToast({
          title: '请输入正确的手机号',
          icon: 'none'
        });
        return;
      }

      if (!currentAddress.address) {
        wx.showToast({
          title: '请填写详细地址',
          icon: 'none'
        });
        return;
      }

      let newAddressList = [...addressList];

      if (isEdit) { //更新
        newAddressList[editIndex] = {
          ...currentAddress
        };
      } else { //新增
        newAddressList.push({
          ...currentAddress,
          id: Date.now()
        });
      }
      api.addressAddOrUpdate({
        data: currentAddress
      }).then((res) => {
        this.setData({
          addressList: newAddressList,
          showModal: false
        });

        this.triggerEvent('change', {
          addressList: newAddressList
        });
      })
    },
    onSelectOk(e) {
      const index = e.currentTarget.dataset.index;
      const currentAddress = this.data.addressList[index];
      if (this.data.modalType == 2) {//选择模式
        this.triggerEvent('selected', {//
          currentAddress
        });
      } 
    }
  }
});